# -*- coding: UTF-8 -*-
"""
@Project : Fast
@File    : .py
@IDE     : PyCharm
@Author  : xuan
@Date    : 2024/2/4 16:33
"""
from loguru import logger
from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.responses import Response


class LoggingMiddleware(BaseHTTPMiddleware):

    async def dispatch(
            self, request: Request, call_next: RequestResponseEndpoint
    ) -> Response:
        # 处理请求前的日志记录逻辑
        logger.info(f"Request: {request.method} {request.url}")
        response = await call_next(request)

        # 处理请求后的日志记录逻辑
        logger.info(f"Response: {response.status_code}")

        # # 记录 Response内容
        # response_body = await response.body()
        # try:
        #     response_body_str = await response_body.decode("utf-8")
        #     logger.info(f"Response Body: {response_body_str}")
        # except UnicodeDecodeError as e:
        #     # 如果无法解码为 UTF-8 字符串，则将其记录为二进制数据
        #     logger.info("Response Body (Binary): <binary data>")

        return response

# loging_middleware = LoggingMiddleware(BaseHTTPMiddleware)
